package com.ttdevs.spring.controller;

import com.ttdevs.spring.model.Operate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * RESTful with JSON
 */

@Controller
@RequestMapping(value = "/restful")
public class RESTFulJSONController {

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody Operate create(@ModelAttribute Operate professionalForm, BindingResult result, Model model, @RequestBody String body) {
        Operate operate = new Operate();
        operate.setMethod(RequestMethod.POST.name());
        operate.setParamter(null);
        operate.setRequest(body);
        operate.setResponse("create object");

        return operate;
    }

    @RequestMapping(value = "/{param}", method = {RequestMethod.GET})
    public
    @ResponseBody
    Object retrieve(@PathVariable String param) { // @PathVariable() String param or @PathVariable("param") String param
        if (param.isEmpty()) {
            return "{\"error:\" : \"param is null\"}";
        }
        Operate operate = new Operate();
        operate.setMethod(RequestMethod.GET.name());
        operate.setParamter(param);
        operate.setRequest(null);
        operate.setResponse("retrieve objects with " + param);

        return operate;
    }

    @RequestMapping(value = "/{param}", method = {RequestMethod.PUT})
    public
    @ResponseBody
    Operate update(@PathVariable("param") String param, @RequestBody String body) {
        Operate operate = new Operate();
        operate.setMethod(RequestMethod.PUT.name());
        operate.setParamter(param);
        operate.setRequest(body);
        operate.setResponse("update object with " + param);

        return operate;
    }

    @RequestMapping(value = "/{param}", method = {RequestMethod.DELETE})
    public
    @ResponseBody
    Operate delete(@PathVariable("param") String param) {
        Operate operate = new Operate();
        operate.setMethod(RequestMethod.DELETE.name());
        operate.setParamter(param);
        operate.setRequest(null);
        operate.setResponse("delete object with " + param);

        return operate;
    }

    @ExceptionHandler({RuntimeException.class})
    public
    @ResponseBody
    String exception(Exception e) {
        return "{" + e.getMessage() + "}";
    }
}
